# 图片识别

import json
import os
import sys
import threading
import time

import keyboard
import pyautogui

from app import monitor_screen


def ms_to_seconds(ms):
    return ms / 1000.0

def load_config(file_path):
    with open(file_path, 'r') as f:
        return json.load(f)

def auto_click_sequence(stop_event, config):
    click_sequence = config['click_sequence']
    # interval_ms = config['interval_ms']
    repeat_times = config['repeat_times']
    screen_config = config['screen_capture']

    try:
        print("当前使用的配置:")
        for i, click in enumerate(click_sequence, 1):
            print(f"第{i}个点击位置: {click['position']}, 等待时间: {click['wait_time']}毫秒")
        # print(f"下一次循环等待时间: {interval_ms}毫秒")
        print(f"重复次数: {repeat_times}次\n")

        print(f"程序将在3000毫秒后开始执行...")
        time.sleep(ms_to_seconds(3000))

        for i in range(repeat_times):
            if stop_event.is_set():
                print("检测到停止信号，退出自动点击。")
                break

            print(f"\n开始执行第 {i + 1}/{repeat_times} 次序列")

            for j, click in enumerate(click_sequence, 1):
                pos = click['position']
                wait = click['wait_time']
                pyautogui.moveTo(pos[0], pos[1], duration=0.5)
                pyautogui.click()
                # print(f"点击位置 {j}: {pos}")
                if j < len(click_sequence):
                    # print(f"等待 {wait} 毫秒")
                    time.sleep(ms_to_seconds(wait))

            if i < repeat_times - 1:
                while True:
                    if stop_event.is_set():
                        print("检测到停止信号，退出自动点击。")
                        break
                    if monitor_screen(screen_config):
                        break
        print("\n所有点击序列执行完成！")

    except pyautogui.FailSafeException:
        print("触发了故障保护，程序已停止")

# 定义一个监听键盘事件的函数
# 监听 Ctrl+Z 并退出程序的函数
def listen_for_ctrl_z(stop_event):
    print("按Ctrl+Z退出程序...")
    while True:
        if keyboard.is_pressed('ctrl+z'):  # 检测是否按下Ctrl+Z
            print("检测到Ctrl+Z，程序正在退出...")
            stop_event.set()  # 设置事件，通知主线程停止
            sys.exit(0)

if __name__ == "__main__":
    i = input("输入1开始自动点击，输入其他数字退出：")
    if i == '1':
        try:
            base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
            configh_path = os.path.join(base_path, 'config.json')
            config = load_config(configh_path)

            # 创建一个 Event 对象，用于控制停止信号
            stop_event = threading.Event()

            # 启动一个线程来监听Ctrl+Z
            threading.Thread(target=listen_for_ctrl_z, args=(stop_event,), daemon=True).start()
            auto_click_sequence(stop_event, config)
        except Exception as e:
            print(f"程序执行失败: {str(e)}")
    else:
        exit()


